package com.hissagetest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

class SmsData {
	private List<String> smsList = new ArrayList<String>() ;
	private static SmsData singleton = null;
	
	private SmsData() {
	} ;
	
	private void _read() {
		try {
			ObjectInputStream inPut = new ObjectInputStream(new FileInputStream(android.os.Environment.getExternalStorageDirectory() + "/smsList.dat")) ; 
			smsList = (ArrayList<String>)inPut.readObject() ;
			inPut.close() ;
		} 
		catch (FileNotFoundException e) {
			Log.i("SmsList", "smsList.dat is not found") ;
		}
		catch (Exception e) {
			e.printStackTrace() ;
		}
	} ;
	
	private void _save() {
		try {
			ObjectOutputStream outPut = new ObjectOutputStream(new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + "/smsList.dat"));
			outPut.writeObject(smsList) ;
			outPut.close() ;
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	} ;
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		_save() ;
	} ;
	
	public static List<String> getSmsList() {
		
		if (singleton == null) {
			singleton = new SmsData() ;
			singleton._read() ;
		}
		
		return singleton.smsList ;
	} ;
	
	public static void addSmsData(Bundle data) {
		
		if (singleton == null) {
			singleton = new SmsData() ;
			singleton._read() ;
		}
		
    	if (data != null) {
    		Object[] pdus = (Object[]) data.get("pdus");
    		for (int i = 0; i < pdus.length; i++) {
    			SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]) ;
    			singleton.smsList.add("From:" + message.getOriginatingAddress() + "  Body:" + message.getMessageBody()) ;
    		}
    	}
    	
    	singleton._save() ;
	} ;
}

public class HelloSms extends Activity {

	private Button backButton, sendIntentButton ;
	private ListView listView ;
	private HelloSms self ;
	private int result;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smslist);
        self = this ;
        backButton = (Button)findViewById(R.id.backButton) ;
        backButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent() ;
				intent.putExtra("result", (result == 1) ? "with sms back" : "normal back") ;
				self.setResult(result,intent) ;
				self.finish() ;
			}
		}) ;
        
        sendIntentButton = (Button)findViewById(R.id.sendIntentButton) ;
        sendIntentButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent() ;
				intent.setAction("android.intent.action.INSERT") ;
				Uri uri = Uri.parse("content://com.google.provider.NotePad/notes");
				intent.setData(uri) ;
				startActivity(intent) ;
			}
		}) ;
        
        Bundle bundle = this.getIntent().getExtras();
	    if (bundle != null) {
	    	SmsData.addSmsData(bundle.getBundle("smsData")) ;
	    	result = 1 ;
	    } else {
	    	result = 0 ;
	    }
	    
	    listView = (ListView)findViewById(R.id.smsListView) ;
	    listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, _getData()));
	    
	    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
				Log.i("SmsList", String.format("onItemClick is call position = %d, id = %d", position, id)) ;
				// Toast.makeText(getApplicationContext(), smsList.get(position), Toast.LENGTH_LONG).show();
				LayoutInflater inflater = getLayoutInflater();
				View layout = inflater.inflate(R.layout.test_toast,
				                               (ViewGroup) findViewById(R.id.test_toast_root));

				TextView title = (TextView) layout.findViewById(R.id.title);
				title.setText("ItemClick");
				
				TextView body = (TextView) layout.findViewById(R.id.body);
				body.setText(SmsData.getSmsList().get(position));

				Toast toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				toast.setDuration(Toast.LENGTH_LONG);
				toast.setView(layout);
				toast.show();
			}
	    }) ;
    }
    
    @Override
    public void onResume() {
    	super.onResume() ;
    	HelloBroadcastRecv.setCurActivity(self) ;
    }
    
    public void onStop() {
    	super.onStop() ;
    }
    
    private List<String> _getData(){
    	return SmsData.getSmsList() ;
    }
    
    public final void onSmsReceive(Intent data) {
    	SmsData.addSmsData(data.getExtras()) ;
    	ArrayAdapter<String> adapter = (ArrayAdapter<String>)listView.getAdapter();
    	adapter.notifyDataSetChanged();
    	onResume() ;
    }
    
    public  static void onStaticSmsReceive(Intent data) {
    	SmsData.addSmsData(data.getExtras()) ;
    }
}
